package cn.xuewenbao.edu.service.impl;

import cn.xuewenbao.edu.controller.ESController;
import cn.xuewenbao.edu.entity.*;
import cn.xuewenbao.edu.entity.vo.*;
import cn.xuewenbao.edu.mapper.JournalMapper;
import cn.xuewenbao.edu.mapper.JournalSubjectMapper;
import cn.xuewenbao.edu.service.*;
import cn.xuewenbao.ucenter.service.MemberService;
import cn.xuewenbao.ucenter.service.VipService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import lombok.val;
import org.jeecg.common.api.vo.Result;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * <p>
 * 期刊表 服务实现类
 * </p>
 *
 * @author mafayu
 * @since 2021-03-30
 */
@Service
@Slf4j
public class JournalServiceImpl extends ServiceImpl<JournalMapper, Journal> implements JournalService {

    private static final String JOURNAL_TYPE = "3";

    @Autowired
    private JournalSubjectService journalSubjectService;

    @Autowired
    private MemberService memberService;

    @Autowired
    private ColumnDataService columnDataService;

    @Autowired
    private LikeContentService likeContentService;

    @Autowired
    private FavoriteService favoriteService;

    @Autowired
    private JournalSubjectMapper journalSubjectMapper;

    @Autowired
    private VipService vipService;

    @Autowired
    private ContentSubjectService contentSubjectService;

    @Autowired
    private ESController esController;

    @Autowired
    private ViewContentService viewContentService;

    //根据期刊id返回最新一期的期刊首页
    @Override
    public Result<JournalIndexVo> getLatestJournalList(String journalId) {
        Result<JournalIndexVo> result = new Result<>();
        Journal journal = baseMapper.selectById(journalId);
        if (journal == null) {
            result.setSuccess(false);
            result.setMessage("期刊不存在");
            return result;
        }
        //得到最新期刊号
        String[] date = journal.getNumber().split(",");
        String number = date[0];
        //得到期刊号下面的内容
        QueryWrapper<JournalSubject> wrapper = new QueryWrapper<>();
        wrapper.eq("parent_id", journalId).eq("number", number);
        List<JournalSubject> journalSubjectList = journalSubjectService.list(wrapper);
        List<JouanalSubjectVo> subjectVoList = new ArrayList<>();
        for (int i = 0; i < journalSubjectList.size(); i++) {
            JournalSubject journalSubject = journalSubjectList.get(i);
            //根据id得到作者用户名
            String[] authors = journalSubject.getAuthorId().split(",");
            List<String> authorList = new ArrayList<>();
            for (String authorId : authors) {
                authorList.add(memberService.getById(authorId).getUsername());
            }
            JouanalSubjectVo jouanalSubjectVo = new JouanalSubjectVo();
            BeanUtils.copyProperties(journalSubject, jouanalSubjectVo);
            jouanalSubjectVo.setAuthorName(authorList);
            subjectVoList.add(jouanalSubjectVo);
        }
        JournalIndexVo journalIndexVo = new JournalIndexVo();
        BeanUtils.copyProperties(journal, journalIndexVo);
        journalIndexVo.setSubjectVoList(subjectVoList);
        result.setResult(journalIndexVo);
        result.setSuccess(true);
        return result;
    }

    //根据期刊id和期号, 返回指定期号的期刊首页
    @Override
    public Result<JournalIndexVo> getJournalList(String journalId, String number) {
        Result<JournalIndexVo> result = new Result<>();
        Journal journal = baseMapper.selectById(journalId);
        if (journal == null) {
            result.setSuccess(false);
            result.setMessage("期刊不存在");
            return result;
        }
        //得到期刊号下面的内容
        QueryWrapper<JournalSubject> wrapper = new QueryWrapper<>();
        wrapper.eq("parent_id", journalId).eq("number", number);
        List<JournalSubject> journalSubjectList = journalSubjectService.list(wrapper);
        List<JouanalSubjectVo> subjectVoList = new ArrayList<>();
        for (int i = 0; i < journalSubjectList.size(); i++) {
            JournalSubject journalSubject = journalSubjectList.get(i);
            //根据id得到作者用户名
            String[] authors = journalSubject.getAuthorId().split(",");
            List<String> authorList = new ArrayList<>();
            for (String authorId : authors) {
                authorList.add(memberService.getById(authorId).getUsername());
            }
            JouanalSubjectVo jouanalSubjectVo = new JouanalSubjectVo();
            BeanUtils.copyProperties(journalSubject, jouanalSubjectVo);
            jouanalSubjectVo.setAuthorName(authorList);
            subjectVoList.add(jouanalSubjectVo);
        }
        JournalIndexVo journalIndexVo = new JournalIndexVo();
        BeanUtils.copyProperties(journal, journalIndexVo);
        journalIndexVo.setSubjectVoList(subjectVoList);
        result.setResult(journalIndexVo);
        result.setSuccess(true);
        return result;
    }

    //根据期刊id和期刊号返回期刊列表
    @Override
    public Result<List<JouanalSubjectVo>> getConcreteJournal(String journalId, String number) {
        Result<List<JouanalSubjectVo>> result = new Result<>();
        //得到期刊号下面的内容
        QueryWrapper<JournalSubject> wrapper = new QueryWrapper<>();
        wrapper.eq("parent_id", journalId).eq("number", number);
        List<JournalSubject> journalSubjectList = journalSubjectService.list(wrapper);
        if (journalSubjectList.isEmpty()) {
            result.setSuccess(false);
            return result;
        }
        List<JouanalSubjectVo> subjectVoList = new ArrayList<>();
        for (int i = 0; i < journalSubjectList.size(); i++) {
            JournalSubject journalSubject = journalSubjectList.get(i);
            //根据id得到作者用户名
            String[] authors = journalSubject.getAuthorId().split(",");
            List<String> authorList = new ArrayList<>();
            for (String authorId : authors) {
                authorList.add(memberService.getById(authorId).getUsername());
            }
            JouanalSubjectVo jouanalSubjectVo = new JouanalSubjectVo();
            BeanUtils.copyProperties(journalSubject, jouanalSubjectVo);
            jouanalSubjectVo.setAuthorName(authorList);
            subjectVoList.add(jouanalSubjectVo);
        }
        result.setSuccess(true);
        result.setResult(subjectVoList);
        return result;
    }

    //根据期刊id返回期刊所有期刊号
    @Override
    public Result<List<String>> getJournalNumber(String journalId) {
        Result<List<String>> result = new Result<>();
        Journal journal = baseMapper.selectById(journalId);
        if (journal == null) {
            result.setSuccess(false);
            return result;
        }
        List<String> list = Arrays.asList(journal.getNumber().split(","));
        result.setResult(list);
        result.setSuccess(true);
        return result;
    }

    @Override
    public Result<JournalDetailVo> getJournalDetail(String journalSubjectId, String userId) {
        Result<JournalDetailVo> result = new Result<>();
        JournalSubject journalSubject = journalSubjectMapper.selectById(journalSubjectId);
        if (journalSubject == null) {
            result.setSuccess(false);
            result.setMessage("期刊内容不存在");
            return result;
        }
        //阅读数加1
        journalSubject.setViewCount(journalSubject.getViewCount()+1);
        journalSubjectService.updateById(journalSubject);

        //将阅读记录添加到阅读表中
        ViewContent viewContent = new ViewContent();
        viewContent.setContentId(journalSubjectId);
        viewContent.setColumnType(JOURNAL_TYPE);
        viewContent.setAuthorId(journalSubject.getAuthorId());
        viewContent.setUserId(userId);
        viewContentService.save(viewContent);

        JournalDetailVo journalDetailVo = new JournalDetailVo();
        BeanUtils.copyProperties(journalSubject, journalDetailVo);
        // 查询作者姓名List
        String[] authors = journalSubject.getAuthorId().split(",");
        List<String> authorList = new ArrayList<>();
        for (String authorId : authors) {
            authorList.add(memberService.getById(authorId).getUsername());
        }
        journalDetailVo.setAuthorName(authorList);
        //查询是否点赞、收藏
        Result<?> isLikeResult = likeContentService.hasLikeOne(userId, journalSubjectId, JOURNAL_TYPE);
        journalDetailVo.setIsLike(isLikeResult.isSuccess());
        Result<?> isFavoriteResult = favoriteService.hasFavoriteOne(userId, journalSubjectId, JOURNAL_TYPE);
        journalDetailVo.setIsFavorite(isFavoriteResult.isSuccess());
        //查询该期刊的点赞数、收藏数
        QueryWrapper<ColumnData> wrapper = new QueryWrapper<>();
        wrapper.eq("content_id", journalSubjectId).eq("column_type", JOURNAL_TYPE);
        ColumnData columnData = columnDataService.getOne(wrapper);
        if (columnData == null) {
            result.setSuccess(false);
            result.setMessage("期刊内容的数据不存在");
            return result;
        }

        columnData.setViewCount(journalSubject.getViewCount());
        columnDataService.updateById(columnData);

        journalDetailVo.setLikeCount(columnData.getLikeCount());
        journalDetailVo.setFavoriteCount(columnData.getFavoriteCount());
        //获取该用户是否有会员权限查看
        boolean isVip = vipService.isVip(userId);
        journalDetailVo.setIsVip(isVip);
        result.setResult(journalDetailVo);
        result.setSuccess(true);
        return result;
    }

    @Override
    public Result<?> getJournalColumnList() {
        Result<List<JournalColumnVo>> result = new Result<>();
        List<JournalColumnVo> voList = new ArrayList<>();
        //分组查询出所有期刊的 id和 期刊号, from journal_subject
        QueryWrapper<JournalSubject> wrapper = new QueryWrapper<>();
        wrapper.select("parent_id", "number").groupBy("parent_id", "number").orderByDesc("number");
        List<JournalSubject> journalSubjects = journalSubjectMapper.selectList(wrapper);
        if (journalSubjects == null || journalSubjects.size() == 0) {
            result.setSuccess(false);
            result.setMessage("未找到期刊专栏页数据");
            return result;
        }
        for (JournalSubject subject : journalSubjects) {
            JournalColumnVo vo = new JournalColumnVo();
            vo.setId(subject.getParentId());
            vo.setNumber(subject.getNumber());
            QueryWrapper<Journal> journalWrapper = new QueryWrapper<>();
            journalWrapper.select("title", "cover").eq("id", subject.getParentId());
            Journal journal = baseMapper.selectOne(journalWrapper);
            vo.setTitle(journal.getTitle());
            vo.setCover(journal.getCover());
            List<JouanalSubjectVo> subjectVoList = new ArrayList<>();
            QueryWrapper<JournalSubject> journalSubjectWrapper = new QueryWrapper<>();
            journalSubjectWrapper.select("id", "sub_title").eq("parent_id", vo.getId()).eq("number", vo.getNumber()).last("limit 3");
            List<JournalSubject> subjects = journalSubjectMapper.selectList(journalSubjectWrapper);
            for (JournalSubject journalSubject : subjects) {
                JouanalSubjectVo subjectVo = new JouanalSubjectVo();
                BeanUtils.copyProperties(journalSubject, subjectVo);
                subjectVoList.add(subjectVo);
            }
            vo.setSubjectVoList(subjectVoList);
            voList.add(vo);
        }
        result.setSuccess(true);
        result.setResult(voList);
        return result;
    }

    @Override
    public Journal getJournalTitleAndCoverByJournalId(String id) {
        QueryWrapper<Journal> wrapper = new QueryWrapper<>();
        wrapper.select("title", "cover").eq("id", id);
        return baseMapper.selectOne(wrapper);
    }

    @Override
    public Result<?> addJournalSubject(JournalPublishVo vo) {
        Result<JournalPublishVo> result = new Result<>();
        QueryWrapper<Journal> journalWrapper = new QueryWrapper<>();
        journalWrapper.eq("title", vo.getTitle());
        Journal journal = baseMapper.selectOne(journalWrapper);
        //添加或更新journal
        if (journal == null) {  //journal不存在, 添加journal
            Journal newJournal = new Journal();
            BeanUtils.copyProperties(vo, newJournal);
            newJournal.setViewCount(0L);
            int insert = baseMapper.insert(newJournal);
            if (insert == 0) {
                result.setSuccess(false);
                result.setMessage("添加期刊失败");
                return result;
            }
            //将发布的期刊添加到ES
            ESEntity esEntity = new ESEntity();
            BeanUtils.copyProperties(journal,esEntity);
            esEntity.setColumnType(JOURNAL_TYPE);
            try {
                esController.addDoc("test",esEntity);
            } catch (IOException e) {
                log.error(e.toString());
            }
            final val id = newJournal.getId();
            //添加三级分类
            val subjectList = vo.getSubjectList();
            for (String s : subjectList) {
                ContentSubject contentSubject = new ContentSubject();
                contentSubject.setContentId(id);
                contentSubject.setSubjectId(s);
                contentSubject.setColumnType(JOURNAL_TYPE);
                contentSubjectService.save(contentSubject);
            }
            vo.setId(id);
        } else {     //journal已存在, 查看新添加的期刊号是否已存在
            String numbers = journal.getNumber();
            int index = numbers.indexOf(vo.getNumber());
            //未找到新添加的期刊号, 将新期刊号更新至journal
            if (index == -1) {
                journal.setNumber(numbers + "," + vo.getNumber());
                UpdateWrapper<Journal> updateWrapper = new UpdateWrapper<>();
                updateWrapper.eq("id", journal.getId());
                int update = baseMapper.update(journal, updateWrapper);
                if (update <= 0) {
                    result.setSuccess(false);
                    result.setMessage("向journal添加新期刊号失败");
                    return result;
                }
            }
            vo.setId(journal.getId());
        }
        //添加journal_subject
        JournalSubject journalSubject = new JournalSubject();
        BeanUtils.copyProperties(vo, journalSubject);   //会把journal的id 传给journal_subject
        journalSubject.setId(null);
        journalSubject.setParentId(vo.getId());
        journalSubject.setViewCount(Long.valueOf(0));
        int insert = journalSubjectMapper.insert(journalSubject);
        if (insert == 0) {
            result.setSuccess(false);
            result.setMessage("添加journal_subject失败");
            return result;
        }
        Boolean dataInsertSuccess = columnDataService.addColumnData(journalSubject.getId(), JOURNAL_TYPE, 0L, 0L, 0L, 0L);
        if (!dataInsertSuccess) {
            return Result.error("添加期刊内容数据失败");
        }
        //将发布的journal_subject添加到ES
        ESEntity esEntity = new ESEntity();
        BeanUtils.copyProperties(journalSubject,esEntity);
        esEntity.setColumnType(JOURNAL_TYPE);
        String userName="";
        for (String s : journalSubject.getAuthorId().split(",")) {
            String username=memberService.getUserNameById(s);
            userName = userName+","+username;
        }
        esEntity.setUserName(userName);
        try {
            esController.addDoc("test",esEntity);
        } catch (IOException e) {
            log.error(e.toString());
        }
        result.setSuccess(true);
        result.setMessage("添加期刊成功");
        result.setResult(vo);
        return result;
    }

//    //删除期刊
//    @Override
//    public Result<?> deleteJournal(String journalId) {
//        Result<?> result = new Result<>();
//        int res = baseMapper.deleteById(journalId);
//        if (res == 0) {
//            result.setMessage("删除期刊失败");
//            result.setSuccess(false);
//            return result;
//        }
//        result.setMessage("删除期刊成功");
//        result.setSuccess(true);
//        return result;
//    }

}
